import store from './Store.module.css'
import ContentTop from '../../components/ContentTop';
import React, { useEffect, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
    Button, Checkbox, Form, Input, InputNumber,
    Upload, TimePicker, Flex, message,
} from 'antd';
import dayjs from 'dayjs';
import { editStore, getStore, uploadImage } from '../../api/account';


export default function Shop() {
    const { TextArea } = Input;
    const [form] = Form.useForm();
    const [img, setImg] = useState('')
    const [imageValue, setImageValue] = useState('');
    const plainOptions = ['单人精彩套餐', 'VC无限橙果汁全场8折', '在线支付满28减5',
        '特价饮品八折抢购', '中秋特惠', '国庆特价', '春节1折折扣'];
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [pics, setPics] = useState([{ url: '' }]);
    const [id, setId] = useState('')
    const handleChange = ({ fileList: newFileList }) => {
        setPics(newFileList)
    };
    useEffect(() => {
        form.setFieldValue('pics', pics)
    }, [pics.length]);
    const uploadButton = (
        <button style={{ border: 0, background: 'none', }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8, }}>
                Upload
            </div>
        </button>
    );
    //照片上传接口
    const handleRequest = async (file, values) => {
        const formData = new FormData();
        formData.append('file', file);
        let res = await uploadImage(formData)
        if (res.data.code == 0) {
            if (values == 2) {//头像上传
                setImageValue(res.data.imgUrl);
                form.setFieldValue('avatar', res.data.imgUrl.replace('/upload/shop/', ''))
                message.success('上传成功');
            } else if (values == 1) {//店铺图片上传
                let newpics = pics
                newpics.pop();
                setImg(res.data.imgUrl);
                const newPic = { url: 'http://8.137.157.16:9002' + res.data.imgUrl };
                newpics = [...newpics, newPic];
                setPics(newpics)
                message.success('上传成功');
                setTimeout(() => {
                    form.setFieldValue('pics', newpics)
                }, 1000);
            }
        } else {
            message.error('上传失败')
        }
    }
    //编辑上传
    const toEdit = async () => {
        const formValues = form.getFieldsValue();
        const newformValues = { ...formValues, id: id };
        if (formValues.avatar.startsWith('http://8.137.157.16:9002/upload/shop/')) {
            newformValues.avatar = formValues.avatar.replace('http://8.137.157.16:9002/upload/shop/', '');
        } else {
            newformValues.avatar = formValues.avatar.replace('/upload/shop/', '');
        }
        let urls = newformValues.pics.map(item => item.url.replace('http://8.137.157.16:9002/upload/shop/', ''));
        newformValues.pics = JSON.stringify(urls);
        let time = newformValues.date.map(item => item.format('YYYY-MM-DD HH:mm:ss'));
        newformValues.date = JSON.stringify(time);
        newformValues.supports = JSON.stringify(newformValues.supports);
        let res = await editStore(newformValues);
        if (res.data.code == 0) {
            message.success('修改成功');
        }
    }
    //初始值请求
    useEffect(() => {
        getStore().then(res => {
            let data = res.data.data;
            form.setFieldsValue({
                name: data.name,
                bulletin: data.bulletin,
                avatar: data.avatar,
                description: data.description,
                date: [dayjs(data.date[0]), dayjs(data.date[1])],
                deliveryPrice: data.deliveryPrice,
                deliveryTime: data.deliveryTime,
                contact_phone: data.contact_phone,
                minPrice: data.minPrice,
                score: data.score,
                sellCount: data.sellCount,
                supports: data.supports,
                pics: data.pics
            })
            setId(data.id)
            setImageValue(data.avatar)
            setPics(data.pics.map(item => ({ url: 'http://8.137.157.16:9002' + item })))
        })
    }, [])
    return (
        <>
            <ContentTop>
                <div className="title">
                    店铺管理
                </div>
                <div className="btn">
                    <Button type="primary" onClick={() => toEdit()}>保存店铺信息</Button>
                </div>
            </ContentTop>
            <Form
                layout="horizontal"
                className={store.total}
                form={form}
            >
                <Form.Item label="店铺名称" name='name'>
                    <Input />
                </Form.Item>
                <Form.Item label="店铺公告" name='bulletin'>
                    <TextArea rows={2} />
                </Form.Item>
                <Form.Item label="店铺头像" name="avatar">
                    <Flex gap="middle" wrap="wrap" className={store.fabox}>
                        <img
                            src={'http://8.137.157.16:9002' + imageValue}
                            className={store.img}
                        />
                        <Upload
                            className={`avatar-uploader ${store.upload}`}
                            customRequest={({ file }) => handleRequest(file, 2)}
                            showUploadList={false}>
                            <button
                                className={store.uploadBtn}
                                type="button">
                            </button>
                        </Upload>
                    </Flex>
                </Form.Item>
                <Form.Item label="店铺图片" valuePropName="pics" name='pics'>
                    <div>
                        <Upload
                            listType="picture-card"
                            fileList={pics}
                            onChange={handleChange}
                            customRequest={({ file }) => handleRequest(file, 1)}>
                            {pics.length >= 8 ? null : uploadButton}
                        </Upload>
                        {previewImage && (
                            <Image wrapperStyle={{ display: 'none' }}
                                preview={{
                                    visible: previewOpen,
                                    onVisibleChange: (visible) => setPreviewOpen(visible),
                                    afterOpenChange: (visible) => !visible && setPreviewImage(''),
                                }}
                                src={previewImage}
                            />
                        )}
                    </div>
                </Form.Item>
                <Form.Item label="起送价格" name='minPrice'>
                    <InputNumber min={1} />
                </Form.Item>
                <Form.Item label="配送费" name='deliveryPrice'>
                    <InputNumber min={1} />
                </Form.Item>
                <Form.Item label="送达时间" name='deliveryTime'>
                    <InputNumber min={1} />
                </Form.Item>
                <Form.Item label="配送描述" name='description'>
                    <Input />
                </Form.Item>
                <Form.Item label="店铺好评率" name='score'>
                    <InputNumber min={0} />
                </Form.Item>
                <Form.Item label="店铺销量" name='sellCount'>
                    <InputNumber min={1} />
                </Form.Item>
                <Form.Item label="活动支持" name='supports'>
                    <Checkbox.Group options={plainOptions} />
                </Form.Item>
                <Form.Item label="营业时间" name='date'>
                    <TimePicker.RangePicker />
                </Form.Item>
            </Form>
        </>
    )
}
